package cs633.action;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.struts2.interceptor.ServletRequestAware;

import com.opensymphony.xwork2.ActionSupport;

import cs633.util.Album;
import cs633.util.DBManager;
import cs633.util.Photo;
import cs633.util.Utils;

public class UserAlbumsAction extends ActionSupport implements ServletRequestAware {
	private static final long serialVersionUID = 7524102511514266657L;
	private HttpServletRequest request;
	private List<Album> albumList;
	private List<Photo> photoList;
/*	
	public String userPhotos() {
		Photo photo = null;
		String userId = request.getParameter("userId");
		String albumName = request.getParameter("albumName");
		HttpSession session = request.getSession(false);
		Connection con = null;	
		List<Photo> aList = new ArrayList<Photo>();
		
		try {
			con = DBManager.getInstance().getConn();
			String sql = "SELECT A.ALBUM_LOC, B.IMG_NAME, B.IMG_TITLE, B.IMG_DESC FROM USER_ALBUM A, USER_IMG B, USER C " +
					"WHERE A.USER_ALBUM_ID = B.USER_ALBUM_ID AND C.USER_SEQ_ID = A.USER_SEQ_ID AND C.USER_ID = ? AND A.ALBUM_NAME = ?";			
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setString(1, userId);
			pstmt.setString(2, albumName);
			
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				photo = new Photo();
				photo.setAlbumLoc(rs.getString("ALBUM_LOC"));
				photo.setPhotoName(rs.getString("IMG_NAME"));
				photo.setPhotoTitle(rs.getString("IMG_TITLE"));
				photo.setPhotoDesc(rs.getString("IMG_DESC"));
				
				aList.add(photo);
			}
			//setPhotoList(aList);
			session.setAttribute("photos", aList);
			session.setAttribute("albumName", albumName);
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		} finally {
			try {
				con.close();
			} catch (Exception e) {
				
			}
		}
		return SUCCESS;
	}
*/	
	public String userAlbums() {
		HttpSession session = request.getSession(false);
		Album album = null;
		String userId = request.getParameter("userId");
		Connection con = null;
		List<Album> aList = new ArrayList<Album>();
		try {
			con = DBManager.getInstance().getConn();
			String sql = "SELECT B.ALBUM_NAME FROM USER A, USER_ALBUM B WHERE A.USER_ID = ? AND A.USER_SEQ_ID = B.USER_SEQ_ID ORDER BY B.ALBUM_NAME";
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setString(1, userId);
			ResultSet rs = pstmt.executeQuery();
			while (rs.next()) {
				album = new Album();
				album.setAlbumName(rs.getString("ALBUM_NAME"));
				aList.add(album);
			}
			//setAlbumList(aList);
			session.setAttribute("album", aList);
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		} finally {
			try {
				con.close();
			} catch (Exception e) {
				
			}
		}
		return SUCCESS;
	}
	
	public String deleteAlbum() {
		HttpSession session = request.getSession(false);
		String userSeq = (String) session.getAttribute("userSeq");
		String albumName = (String) session.getAttribute("albumName");
		String userId = (String) session.getAttribute("userID");
		Connection con = null;
		String flag = null;
		List<Album> aList = (List<Album>)session.getAttribute("albums");
		Album album = null;
		int albumId = 0;
		for (int i = 0; i < aList.size(); i++) {
			album = aList.get(i);
			if (album.getAlbumName().equals(albumName)) {
				albumId = album.getAlbumId();
				break;
			}
		}
		PreparedStatement pstmt = null;
		try {
			//Album album = Utils.getAlbum(userId, albumName);			
			con = DBManager.getInstance().getConn();		
			String sql = "DELETE FROM USER_IMG WHERE USER_ALBUM_ID = ?";
			pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, albumId);
			int count = pstmt.executeUpdate();
			
			sql = "DELETE FROM USER_ALBUM WHERE USER_SEQ_ID = ? AND ALBUM_NAME = ?";
			pstmt = con.prepareStatement(sql);
			pstmt.setString(1, userSeq);
			pstmt.setString(2, albumName);
			count = pstmt.executeUpdate();
			
			if (count > 0) {
				ResourceBundle rb = ResourceBundle.getBundle("resource");
				String s3 = rb.getString("s3");
				String filePath = s3.concat(File.separator).concat("images").concat(File.separator);
				String albumLoc = album.getAlbumLoc();
				String delLoc = filePath.concat(albumLoc);
				
				File delDir = new File(delLoc);
				if (delDir.exists()) {
					if (delDir.list().length == 0) {
						delDir.delete();
					} else {
						String files[] = delDir.list();
						for (String tmp : files) {
							File fileDel = new File (delDir, tmp);
							fileDel.delete();							
						}
						delDir.delete();
					}
				}
				
				session.removeAttribute("albumName");
				session.setAttribute("albums", Utils.getAlbums(userId));
				flag = SUCCESS;
			} else {
				flag = ERROR;
			}
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
			flag = ERROR;
		} finally {
			try {
				con.close();
			} catch (Exception e) {
				
			}
		}
		return flag;
	}
	
	public String updateAlbum() {
		HttpSession session = request.getSession(false);
		String userSeq = (String) session.getAttribute("userSeq");
		String albumName = (String) session.getAttribute("albumName");
		String userId = (String) session.getAttribute("userID");
		String updatedName = request.getParameter("updateAlbumName");
		
		Connection con = null;
		try {
			con = DBManager.getInstance().getConn();
			String sql = "UPDATE USER_ALBUM SET ALBUM_NAME = ? WHERE USER_SEQ_ID = ? AND ALBUM_NAME = ?";
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setString(1, updatedName);
			pstmt.setString(2, userSeq);
			pstmt.setString(3, albumName);
			int count = pstmt.executeUpdate();
			session.setAttribute("albumName", updatedName);			
			session.setAttribute("albums", Utils.getAlbums(userId));
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		} finally {
			try {
				con.close();
			} catch (Exception e) {
				
			}
		}
		return SUCCESS;
	}
	
	public String publishAlbum() {
		HttpSession session = request.getSession(false);
		String albumName = (String) session.getAttribute("albumName");
		String userSeq = (String) session.getAttribute("userSeq");
		String publish = (String) session.getAttribute("publish");
		
		Connection con = null;
		try {
			con = DBManager.getInstance().getConn();
			String sql = "UPDATE USER_ALBUM SET ALBUM_TYPE = 'U' WHERE USER_SEQ_ID = ? AND ALBUM_NAME = ?";
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, Integer.parseInt(userSeq));
			pstmt.setString(2, albumName);
			pstmt.executeUpdate();			
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		} finally {
			try {
				con.close();
			} catch (Exception e) {
				
			}
		}
		return SUCCESS;
	}
	
	public String unpublishAlbum() {
		HttpSession session = request.getSession(false);
		String albumName = (String) session.getAttribute("albumName");
		String userSeq = (String) session.getAttribute("userSeq");
		
		Connection con = null;
		try {
			con = DBManager.getInstance().getConn();
			String sql = "UPDATE USER_ALBUM SET ALBUM_TYPE = 'R' WHERE USER_SEQ_ID = ? AND ALBUM_NAME = ?";
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, Integer.parseInt(userSeq));
			pstmt.setString(2, albumName);
			pstmt.executeUpdate();			
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		} finally {
			try {
				con.close();
			} catch (Exception e) {
				
			}
		}
		return SUCCESS;
	}
	
	public String newAlbum() {
		HttpSession session = request.getSession(false);

		String userId = (String) session.getAttribute("userID");
		String userSeq = (String) session.getAttribute("userSeq");
		String albumName = request.getParameter("newAlbumName");
		Connection con = null;
		ResourceBundle rb = ResourceBundle.getBundle("resource");
		String s3 = rb.getString("s3");
		
		try {
			String filePath = s3.concat(File.separator).concat("images").concat(File.separator).concat(userId);
			String albumLoc = RandomStringUtils.random(10, true, false);			
			String path = userId + "/" + albumLoc;
			String newAlbumLoc = filePath.concat(File.separator+albumLoc);
			File newDir = new File(newAlbumLoc);
			if (!newDir.exists()) {
				newDir.mkdir();
			}
			
			con = DBManager.getInstance().getConn();
			String sql = "INSERT INTO USER_ALBUM(`USER_SEQ_ID`, `ALBUM_NAME`, `ALBUM_LOC`) VALUES (?, ? ,?)";
			PreparedStatement pstmt = con.prepareStatement(sql);
			pstmt.setInt(1, Integer.parseInt(userSeq));
			pstmt.setString(2, albumName);
			pstmt.setString(3, path);
			
			int count = pstmt.executeUpdate();
			
			session.setAttribute("albums", Utils.getAlbums(userId));
		} catch (Exception e) {
			System.out.println("Error: " + e.getMessage());
		} finally {
			try {
				con.close();
			} catch (Exception e) {
				
			}
		}
		return SUCCESS;
	}
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;	
	}

	public List<Photo> getPhotoList() {
		return photoList;
	}

	public void setPhotoList(List<Photo> photoList) {
		this.photoList = photoList;
	}

	public List<Album> getAlbumList() {
		return albumList;
	}

	public void setAlbumList(List<Album> albumList) {
		this.albumList = albumList;
	}	
}
